//
//  NetWorkManager.m
//  SSFS
//
//  Created by Hero on 16/9/7.
//  Copyright © 2016年 北京山水风尚科技发展有限公司. All rights reserved.
//

#import "NetWorkManager.h"
#import <CommonCrypto/CommonDigest.h>
#import <UIKit/UIKit.h>
#import <MBProgressHUD.h>
#import "UIView+HUD.h"
//#import "UIWindow+Lock.h"
@implementation NetWorkManager

+(instancetype)shareManager{
    static NetWorkManager * manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[self alloc] init];
    });
    return manager;
}

/**
 *
 *  @param url baseUrl
 *
 *  @return 通过重写夫类的initWithBaseURL方法,返回网络请求类的实例
 */

- (instancetype)init{
    if (self = [super init]) {
        /**设置请求超时时间*/
        [self.requestSerializer willChangeValueForKey:@"timeoutInterval"];
        self.requestSerializer.timeoutInterval = 10;
        [self.requestSerializer didChangeValueForKey:@"timeoutInterval"];
        /**设置相应的缓存策略*/
        self.requestSerializer.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
        /**分别设置请求以及相应的序列化器*/
        self.requestSerializer = [AFHTTPRequestSerializer serializer];
        AFJSONResponseSerializer *response = [AFJSONResponseSerializer serializer];
        self.responseSerializer = response;
        AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
        securityPolicy.allowInvalidCertificates = NO;
        securityPolicy.validatesDomainName = YES;
        self.securityPolicy = securityPolicy;
        
        /**设置接受的类型*/
        [self.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"text/plain",@"application/json",@"text/json",@"text/javascript",@"text/html",@"image/jpeg",nil]];
    }
    return self;
}

#pragma mark - 网络请求的类方法---get/post

/**
 *  网络请求的实例方法
 *
 *  @param type         get / post
 *  @param urlString    请求的地址
 *  @param paraments    请求的参数
 *  @param successBlock 请求成功的回调
 *  @param failureBlock 请求失败的回调
 */

+(void)requestWithType:(HttpRequestType)type withUrlString:(NSString *)urlString withParaments:(id)paraments withSuccessBlock:(requestSuccess)successBlock withFailureBlock:(requestFailure)failureBlock progress:(downloadProgress)progress{
    NSString *BaseURL = [us objectForKey:baseUrl];
    NSString *totalUrl = [BaseURL stringByAppendingString:urlString];
    switch (type) {
        case HttpRequestTypeGet:{
            [self setNetworkActivityIndicator:YES];
            [[NetWorkManager shareManager] GET:totalUrl parameters:paraments progress:^(NSProgress * _Nonnull downloadProgress) {
                progress(downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                [self setNetworkActivityIndicator:NO];
                //请求成功
                successBlock(responseObject);
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                [self setNetworkActivityIndicator:NO];
                [[UIApplication sharedApplication].keyWindow showHUDWithTitle:@"网络连接失败,请稍后重试"];
                 //请求失败
                failureBlock(error);
            }];
            break;
        }
        case HttpRequestTypePost:{
            [self setNetworkActivityIndicator:YES];
            [[NetWorkManager shareManager] POST:totalUrl parameters:paraments progress:^(NSProgress * _Nonnull uploadProgress) {
                progress(uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                //请求成功
                [self setNetworkActivityIndicator:NO];
                successBlock(responseObject);
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                //请求失败
                failureBlock(error);
                 [[UIApplication sharedApplication].keyWindow showHUDWithTitle:@"网络连接失败,请稍后重试"];
                [self setNetworkActivityIndicator:NO];
            }];
        }
    }
}


+(void)requestType:(HttpRequestType)type withUrlString:(NSString *)urlString withParaments:(id)paraments withSuccessBlock:(requestSuccess)successBlock withFailureBlock:(requestFailure)failureBlock progress:(downloadProgress)progress
{
    NSString *BaseURL = [us objectForKey:baseUrl];
     NSString *totalUrl = [BaseURL stringByAppendingString:urlString];
    switch (type) {
        case HttpRequestTypeGet:{
            [self setNetworkActivityIndicator:YES];
            [[NetWorkManager shareManager] GET:totalUrl parameters:paraments progress:^(NSProgress * _Nonnull downloadProgress) {
                progress(downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                [self setNetworkActivityIndicator:NO];
                //请求成功
                successBlock(responseObject);
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                [self setNetworkActivityIndicator:NO];
                //请求失败
                 [[UIApplication sharedApplication].keyWindow showHUDWithTitle:@"网络连接失败,请稍后重试"];
                failureBlock(error);
            }];
            break;
        }
        case HttpRequestTypePost:{
            [self setNetworkActivityIndicator:YES];
            [[NetWorkManager shareManager] POST:urlString parameters:paraments progress:^(NSProgress * _Nonnull uploadProgress) {
                progress(uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                //请求成功
                [self setNetworkActivityIndicator:NO];
                successBlock(responseObject);
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                //请求失败
                 [[UIApplication sharedApplication].keyWindow showHUDWithTitle:@"网络连接失败,请稍后重试"];
                failureBlock(error);
                [self setNetworkActivityIndicator:NO];
            }];
        }
    }

}

//+ (void)bodyRequestAgainWithUrl:(NSString *)url parameters:(NSDictionary *)parameters isLoadSession:(BOOL)isLoadSession successBlock:(requestSuccess)success withFailureBlock:(requestFailure)failureBlock{
//    if (isLoadSession) {
//            [self bodyRequestWithUrl:url parameters:parameters successBlock:^(id object) {
//                success(object);
//            } withFailureBlock:^(NSError *error) {
//                failureBlock(error);
//            }];
//        
//    }else{
//        [self bodyRequestWithUrl:url parameters:parameters successBlock:^(id object) {
//            success(object);
//        } withFailureBlock:^(NSError *error) {
//            failureBlock(error);
//        }];
//    }
//}
/**
 *
 **/
//+ (void)bodyRequestWithUrl:(NSString *)url parameters:(NSDictionary* )parameters successBlock:(requestSuccess)success withFailureBlock:(requestFailure)failureBlock{
//    NSData *paraData = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:nil];
//    NSString *paraStr = [[NSString alloc] initWithData:paraData encoding:NSUTF8StringEncoding];
//    dispatch_async(dispatch_get_global_queue(0, 0), ^{
//        NSURLSession *session = [NSURLSession sharedSession];
////        NSURL *totalUrl = [NSURL URLWithString:[BaseURL stringByAppendingString:url]];
////        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:totalUrl];
//        request.HTTPMethod = @"POST";
//        [request setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
////        NSString *sessionId = [us objectForKey:kSessionid]?[us objectForKey:kSessionid]:NULL;
////        NSString *cookie = [NSString stringWithFormat:@"JSESSIONID=%@",sessionId];
////        [request setValue:cookie forHTTPHeaderField:@"Cookie"];
//        request.HTTPBody = [paraStr dataUsingEncoding:NSUTF8StringEncoding];
//        NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//            dispatch_async(dispatch_get_main_queue(), ^{
//                if (data) {
//                    id object = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
//                    if (![object isKindOfClass:[NSArray class]]) {
//                      
//                    }
//                    success(object);
//                }else{
//                    failureBlock(error);
//                }
//            });
//        }];
//        [dataTask resume];
//    });
//}
/**
 *文件上传
 **/
+ (void)uploadImageWithPath:(NSString *)path withImageArray:(NSArray *)imageArray withSuccessBlock:(requestSuccess)successBlock withFailurBlock:(requestFailure)failureBlock withUpLoadProgress:(uploadProgress)progress{
    [[NetWorkManager shareManager] POST:[NSString stringWithFormat:@"%@%@",@"http://139.129.221.194:7777/",@"uploadPictures"] parameters:@{} constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSUInteger i = 0;
        for (UIImage * image in imageArray) {
            NSData *imgData = UIImageJPEGRepresentation(image, 0.1);
            [formData appendPartWithFileData:imgData name:@"files" fileName:[NSString stringWithFormat:@"%@%ld.png",path,(long)i] mimeType:@"image/jpeg"];
            i++;
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        progress(uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
    } success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
        successBlock(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failureBlock(error);
    }];
}
/**
 *身份证上传
 **/
+ (void)uploadIDCardImageWithPath:(NSString *)path withImageArray:(NSArray *)imageArray withSuccessBlock:(requestSuccess)successBlock withFailurBlock:(requestFailure)failureBlock withUpLoadProgress:(uploadProgress)progress{
    [[NetWorkManager shareManager] POST:[NSString stringWithFormat:@"%@%@",@"http://139.129.221.194:7777/",@"identity/ocr"] parameters:@{} constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSUInteger i = 0;
        for (UIImage * image in imageArray) {
            NSData *imgData = UIImageJPEGRepresentation(image, 0.1);
            [formData appendPartWithFileData:imgData name:@"files" fileName:[NSString stringWithFormat:@"%@%ld.png",path,(long)i] mimeType:@"image/jpeg"];
            i++;
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        progress(uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
    } success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
        successBlock(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failureBlock(error);
    }];
}


+ (void)setNetworkActivityIndicator:(BOOL)sign {
    UIApplication *app = [UIApplication sharedApplication];
    [app setNetworkActivityIndicatorVisible:sign];
}
+(NSString*)getCurrentTimestamp{
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a =[dat timeIntervalSince1970];
    NSString*timeString = [NSString stringWithFormat:@"%0.f", a];//转为字符型
    NSString *timeStr13 = [NSString stringWithFormat:@"%@000",timeString];
    return timeStr13;
}

+ (nullable NSString *)md5:(nullable NSString *)str {
    if (!str) return nil;
    
    const char *cStr = str.UTF8String;
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result);
    
    NSMutableString *md5Str = [NSMutableString string];
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; ++i) {
        [md5Str appendFormat:@"%02x", result[i]];
    }
    return md5Str;
}






@end
